<template>
  <div id="wrapper">


    <!-- 初始化头部 -->
    <el-row>
      <el-col :span="16">
        <img src="@/assets/login_logo.png" alt="">
      </el-col>
      <el-col :span="8">
        <div style="margin-top: 15px;">
          <el-input placeholder="请输入你要搜索的商品" style="width:400px;">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div class="cart-header">
        <div class="cart-header-content">
          <p>
            <i class="el-icon-shopping-cart-full" style="color:#ff6700; font-weight: 600;">
            </i>
            我的购物车
          </p>
          <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
        </div>
        <el-button type="danger" class="mainpage" @click="backMain()">返回主页</el-button>
      </div>
    </el-row>
    <!-- 购物车区域 -->
    <el-card>
      <el-table ref="multipleTable" :data="shopcartlist" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column label="全选" type="selection" width="100">
        </el-table-column>
        <el-table-column label="商品详情" width="150" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.goods.goodsImgUrl ? scope.row.goods.goodsImgUrl : ''" alt="" style="width:100px">
          </template>
        </el-table-column>
        <el-table-column label="" width="400">
          <template slot-scope="{row}">
            {{ row.goods.name | upName }}
          </template>
        </el-table-column>

        <el-table-column prop="goods.price" label="商品单价" width="120" align="center">
        </el-table-column>
        <el-table-column label="商品数量" width="180" align="center">
          <template slot-scope="{row}">
            <el-input-number size="mini" v-model="row.quantity" @change="(currentval,oldval) => updateCount(row.goodsId, currentval,oldval)" :min="1"
              :step="1">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="{row}">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeShop(row.id)">删除商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 购物车底部 -->
    <el-card>
      <el-button type="danger" @click="removeIds()">批量删除</el-button>
      <el-button type="primary" @click="emplyCart()">清空购物车</el-button>
      <el-button id="accout" type="danger">去结算</el-button>

      <span>合计：{{ totalprice.toFixed(2) }}元</span>
    </el-card>
  </div>
</template>

<script>







export default {
  name: 'shopCart',
  data() {
    return {
      //封装购物车数据集合
      shopcartlist: [

      ],
      //存储每被选中的商品id
      shopidlist: [],
      //合计总金额
      totalprice: 0,

      //获取当前登录用户
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}, //获取用户
      multipleSelection: [],
      count: 0
    }
  },
  created() {
    this.getShopCart()
  },
  beforeDestroy() {
    this.shopcartlist.forEach(item => {
      this.$API.addGoodsCart(item)
    })

  },
  filters: {
    upName(val) {
      return val.substr(0, 40)
    }
  },
  methods: {
    //获取购物车商品数据
    getShopCart() {

      const userId = this.user.id
      this.$API.getGoodsCart(userId).then(res => {
        this.shopcartlist = res.data
        console.log(this.shopcartlist);


      })

    },
    //计算价格
    updateCount(goodsId, currentval,oldval) {
     
      this.multipleSelection.forEach(item => {
        if (item.goodsId === goodsId) {
          if(currentval>oldval){
            this.totalprice += item.quantity * item.goods.price
          }else{
            this.totalprice-= item.quantity * item.goods.price
          }
          
          
        }
      
      })
      
    },
    //返回主页面
    backMain() {
      this.$router.push('/front')
    },
    // 全选按钮
    handleSelectionChange(val) {

      this.multipleSelection = val
      this.totalprice = 0
      console.log(val);
      this.multipleSelection.forEach(item => {
        this.totalprice += item.quantity * item.goods.price
      })
      console.log("totalprice", this.totalprice);
      console.log("multipleSelection", this.multipleSelection);
    },



    //删除单个商品
    removeShop(goodsId) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API.delSingleShop(goodsId).then(res => {
          if (res.code === "200") {
            this.getShopCart()
            return this.$message.success('删除成功')

          } else {
            return this.$message.error('删除失败')
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除
    removeIds() {

      this.shopidlist = this.multipleSelection.map(item => item.id)
      console.log(this.shopidlist);

      this.$confirm('此操作将永久删除该些商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API.updateCount(this.shopidlist).then(res => {
          if (res.code === "200") {
            this.getShopCart()
            return this.$message.success('批量删除成功')
          } else {
            return this.$message.error('批量删除失败')
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });




    },
    //清空购物车
    emplyCart() {

      const userId = this.user.id
      this.$confirm('此操作将永久清空购物车, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API.delAllShop(userId).then(res => {
          if (res.code === "200") {
            this.getShopCart()
            return this.$message.success('清空成功')
          } else {
            return this.$message.error('清空失败')
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }

  }

}

</script>
<style lang="less" scoped>
#wrapper {
  width: 1200px;
  margin: 0 auto;

  .cart-header {
    margin-top: 20px;
    border-bottom: 5px solid red;
    display: flex;
    justify-content: space-between;

    .mainpage {
      height: 40px !important;
      width: 100px !important;
    }

    .cart-header-content {
      display: flex;


      p {
        font-size: 25px;
      }

      span {
        line-height: 45px;
        color: red;
        margin-left: 15px;
      }
    }
  }

  .el-card {
    margin-top: 20px;

    #accout {
      float: right;
    }

    span {
      float: right;
      line-height: 40px;
    }
  }



}
</style>